package com.hontech.bv.net.device

import com.hontech.bv.codec.encodeUint16
import com.hontech.bv.codec.encodeUint32
import com.hontech.bv.utils.parseJson
import com.hontech.bv.utils.toJson

class Frame (val req: Int, val body: ByteArray?) {

    companion object {

        inline fun <reified T> fromJson(req: Int, v: T): Frame {
            val body = toJson(v)
            return Frame(req, body)
        }
    }

    fun build(): ByteArray {
        val size = 8 + (body?.size ?: 0)
        val buf = ByteArray(size)
        encodeUint16(buf, 0, PROTO_HEAD)
        encodeUint32(buf, 2, size)
        encodeUint16(buf, 6, req)
        if (body != null) {
            System.arraycopy(body, 0, buf, 8, body.size)
        }
        return buf
    }

    inline fun <reified T> parse(): T {
        return parseJson(this.body!!)
    }


}


